// routes/OnlySuperRoute.js
import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from 'contexts/AuthContext';
import { getSuperToken } from 'libs/utils';

// Add a loading component or use an existing one from your project
const LoadingComponent = () => (
  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
    <div>Loading...</div>
  </div>
);

export const OnlySuperRoute = ({ element: Component, ...rest }) => {
  const location = useLocation();
  const { isAuthenticated, user, isLoading } = useAuth();

  // Wait for authentication status to be determined
  if (isLoading) {
    return <LoadingComponent />;
  }

  // Check if user is authenticated
  if (!isAuthenticated) {
    return (
      <Navigate
        to="/auth/login"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  // Check if super token exists
  if (!getSuperToken()) {
    return (
      <Navigate
        to="/auth/login"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  // Check if user role is specifically superadmin
  let allowed = isAuthenticated && user && user.role === 'superadmin';

  if (!allowed) {
    return (
      <Navigate
        to="/plans"
        state={{ from: location.pathname }}
        replace
      />
    );
  }

  return <Component {...rest} />;
};

